package com.example.demo.gw.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Slf4j
@Component
public class UserAuthenticationFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        log.info("============ path:{}", path);
//        RequestPath requestPath = exchange.getRequest().getPath();
//        log.info("============ requestPath:{}",requestPath);
//        Map<String, Object> attributes = exchange.getAttributes();
//        log.info("============ attributes:{}", attributes);
//        exchange.getRequest().getCookies().forEach((key, value) -> {
//            log.info("============ Cookies: {}:{}",key, value);
//        });
//        if (path.equals("/login")) {
//            return chain.filter(exchange);
//        }

//        List<String> authorizations = exchange.getRequest().getHeaders().get("Authorization");
//        if (CollectionUtils.isEmpty(authorizations)) {
//            ServerHttpResponse response = exchange.getResponse();
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("code", HttpStatus.UNAUTHORIZED.value());
//            jsonObject.put("message", HttpStatus.UNAUTHORIZED.series());
//            DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONBytes(jsonObject));
//            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.writeWith(Mono.just(dataBuffer));
//        }

        String csrfToken = UUID.randomUUID().toString();

        ServerHttpRequest request = exchange.getRequest().mutate()
                .header("X-CSRF-TOKEN", csrfToken)
                .header("Authorization", "Bearer " + csrfToken)
                .build();

        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("X-CSRF-TOKEN", csrfToken);
        response.getHeaders().add("Authorization", "Bearer " + csrfToken);

        return chain.filter(exchange.mutate().request(request).response(response).build());
    }
}
